module accel_UART(RX_A, clk, rst_n, Xmeas, accel_vld);

input RX_A, clk, rst_n;

output reg [13:0] Xmeas;

output reg accel_vld;

//////////////////////////////////
// State def;
// LDHI: loads the higher byte
// LDLO: loads the lower byte
//////////////////////////////////
typedef enum reg { LDHI, LDLO } state_t;

state_t state, nxt_state;

logic rx_rdy, rx_clr_rdy;
logic clr_accl_vld, set_accl_vld, ld_lo, ld_hi;
logic [7:0] rx_data;

//////////////////////////////////
// RX unit that will recieve the TX data
//////////////////////////////////
UART_rx rx_unit (.clk(clk), .rst_n(rst_n), .rdy(rx_rdy), .clr_rdy(rx_clr_rdy), .rx_data(rx_data), .RX(RX_A));

////////////////////////////////
// Implementation of state f.f.
////////////////////////////////
always_ff @(posedge clk, negedge rst_n)
   begin
	if(!rst_n)
		state <= LDHI;
	else
		state <= nxt_state;

   end

////////////////////////////////
// Implementation of the high
// byte of Xmeas
////////////////////////////////
always_ff @(posedge clk, negedge rst_n)
   begin
	if(!rst_n)
		Xmeas[13:8] <= 6'h00;
	else if ( ld_hi )
		Xmeas[13:8] <= rx_data[5:0];
   end

////////////////////////////////
// Implements the lower byte
// of Xmeas
////////////////////////////////
always_ff @(posedge clk, negedge rst_n)
   begin
	if(!rst_n)
		Xmeas[7:0] <= 8'h00;
	else if ( ld_lo )
		Xmeas[7:0] <= rx_data[7:0];
   end

////////////////////////////////
// Implements the accel_vld f.f.
////////////////////////////////
always_ff @(posedge clk, negedge rst_n)
   begin
	if(!rst_n)
		accel_vld <= 1'b0;
	else if ( clr_accl_vld )
		accel_vld <= 1'b0;
	else if ( set_accl_vld )
		accel_vld <= 1'b1;
   end

////////////////////////////////////////////////////////////////
// Combinational logic that controls the state machine.
//
// Waits in LDHI for rx_rdy to be asserted by the UART_rx unit.
//  Then clears accel_vld, loads the data form the RX unit into 
//  the higher byte of Xmeas and goes to LDLO state.
// In LDLO state it waits for the next rx_rdy to be asserted by the
//  RX unit. Then it loads the data into the lower byte of Xmeas 
//  and sets accel_vld. Returns to LDHI state.
////////////////////////////////////////////////////////////////
always_comb
   begin
	rx_clr_rdy = 0;
	clr_accl_vld = 0;
	set_accl_vld = 0;
	nxt_state = LDHI;
	ld_hi = 0;
	ld_lo = 0;
	case(state)
	LDHI:
	   begin
		if( rx_rdy )
		   begin
			clr_accl_vld = 1;
			ld_hi = 1;
			rx_clr_rdy = 1;
			nxt_state = LDLO;
		   end
	   end
	LDLO:
	   begin
		if( rx_rdy )
		   begin
			rx_clr_rdy = 1;
			ld_lo = 1;
			set_accl_vld = 1;
			nxt_state = LDHI;
		   end
		else
			nxt_state = LDLO;
	   end
	endcase
   end


endmodule
